<template>
    <div>
        <div>
            <el-config-provider :locale="zhCn"> <!--《:locale="zhCn 》设置语言-->

                <el-scrollbar height="70vh">
                    <!-- 加班申请 -->
                    <el-row :gutter="24">
                        <el-col :span="24">
                            <div class="grid-content ep-bg-purple-light" style="padding: 15px 0;">
                                <el-form-item label="加班申请" label-position="top"
                                    :style="{ fontSize: '15px', fontWeight: 'bold', borderBottom: '1px dashed #e4e7ed' }">
                                    <div class="progress-bar">
                                        <div class="progress"></div>
                                    </div>
                                    <span style="font-size: 12px;">
                                        加班满4 小时，计 0.5 天，满 8 小时，计1 天。<br>
                                        加班时长按照加班天数，以 1:1 的比例，转换为调休时长。
                                    </span>
                                </el-form-item>
                            </div>
                        </el-col>

                        <!--  -->
                        <el-col :span="12">
                            <!-- {{ workingCalendarData }} -->
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="加班单号"
                                    label-position="top">
                                    <el-input placeholder="自动生成无需填写" style="width: 354px;" disabled />
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <!-- {{ overtimeData }} -->
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="姓名" label-position="top">
                                    <el-input placeholder="" :value="user.employeeName" style="/*width: 354px;*/"
                                        disabled />
                                </el-form-item>
                            </div>
                        </el-col>

                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="所在部门"
                                    label-position="top">
                                    <el-input placeholder="" :value="user.department.deptName" style="/*width: 260px;*/"
                                        disabled />
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="申请日期"
                                    label-position="top">
                                    <el-input placeholder="" :value="formData.applicationDate" style="/*width: 260px;*/"
                                        disabled />
                                </el-form-item>
                            </div>
                        </el-col>

                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="加班类型" label-position="top"
                                    required>
                                    <el-select v-model="formData.overtimeType" style="width: 354px;" clearable
                                        filterable disabled>
                                        <el-option label="工作日" value="工作日" />
                                        <el-option label="周末" value="周末" />
                                        <el-option label="法定节假日" value="法定节假日" />
                                    </el-select>
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="归属年份"
                                    label-position="top">
                                    <el-input placeholder="" :value="formData.affiliationYear" style="/*width: 260px;*/"
                                        disabled />
                                </el-form-item>
                            </div>
                        </el-col>

                        <<el-col :span="24">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="加班明细"
                                    label-position="top">
                                    <span style="font-size: 12px;">若有多日需要加班，请按照日期逐日填写！</span>

                                    <el-table :data="overtimeData" border stripe>
                                        <el-table-column fixed type="index" width="50" />
                                        <el-table-column prop="overtimeStartTime" label="加班开始时间" width="200">
                                            <template #default="scope">
                                                <el-date-picker v-model="scope.row.overtimeStartTime" type="datetime"
                                                    value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择开始时间"
                                                    style="width: 100%" @change="calculateOvertimeInfo(scope.$index)"
                                                    :disabled-date="disabledDate" />
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="overtimeEndTime" label="加班结束时间" width="200">
                                            <template #default="scope">
                                                <el-date-picker v-model="scope.row.overtimeEndTime" type="datetime"
                                                    value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择结束时间"
                                                    style="width: 100%" @change="calculateOvertimeInfo(scope.$index)"
                                                    :disabled-date="disabledDate" />
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="week" label="星期" width="160">
                                            <template #default="scope">
                                                <el-input v-model="scope.row.week" disabled style="width: 100%" />
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="overtimeHours" label="加班时长（h）" width="200">
                                            <template #default="scope">
                                                <el-input v-model="scope.row.overtimeHours" disabled
                                                    style="width: 100%" />
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="overtimeDays" label="加班天数" width="200">
                                            <template #default="scope">
                                                <el-input v-model="scope.row.overtimeDays" disabled
                                                    style="width: 100%" />
                                            </template>
                                        </el-table-column>
                                        <el-table-column prop="attendancePeriod" label="归属考勤周期" width="200">
                                            <template #default="scope">
                                                <el-input v-model="scope.row.attendancePeriod" disabled
                                                    style="width: 100%" />
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="操作" width="80">
                                            <template #default="scope">
                                                <el-button size="small" type="danger"
                                                    @click="removeRow(scope.$index)">删除</el-button>
                                            </template>
                                        </el-table-column>
                                    </el-table>

                                </el-form-item>

                                <div class="action-btns" style="margin-top: 12px">
                                    <el-button type="primary" icon="Plus" @click="addRow">
                                        添加
                                    </el-button>
                                </div>
                            </div>
                            </el-col>

                            <!--  -->
                            <el-col :span="24">
                                <!-- 空白分隔区域 -->
                                <div style="height: 10px; border-top: 0px dashed #e4e7ed; margin: 6px 0;"></div>
                            </el-col>

                            <el-col :span="12">
                                <div class="grid-content ep-bg-purple-light"><el-form-item label="加班总天数"
                                        label-position="top">
                                        <el-input v-model="totalOvertimeDays" placeholder="暂无内容"
                                            style="/*width: 260px;*/" disabled />
                                    </el-form-item>
                                </div>
                            </el-col>
                            <el-col :span="12">
                                <div class="grid-content ep-bg-purple-light"><el-form-item label="加班事由"
                                        label-position="top">
                                        <el-input v-model="textarea" style="width: 633px;" :rows="6" type="textarea"
                                            placeholder="" />
                                    </el-form-item>
                                </div>
                            </el-col>

                            <div class="bottom-submit-bar">
                                <el-button type="primary" @click="submitOvertimeApplication">提交</el-button>
                            </div>

                    </el-row>
                </el-scrollbar>

            </el-config-provider>
        </div>
    </div>
</template>

<script setup>
import { ref, watch, defineEmits, onMounted } from 'vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '@/router';
import request from '@/api/request';

let emits = defineEmits(['ref-table']);

// 获取session中的用户信息 - 需要解析JSON字符串
let user = JSON.parse(sessionStorage.getItem('user') || '{}');

const textarea = ref('')
const totalOvertimeDays = ref('')

const formData = ref({})

const workingCalendarData = ref([])

let loadAllWorkingCalendar = () => {
    request({
        url: "/workingCalendar/AllList",
        method: "get"
    }).then(resp => {
        workingCalendarData.value = resp.data
    })
}

const disabledDate = (time) => {
    // 禁用今天之前的日期（不包括今天）
    return time.getTime() < new Date(new Date().setHours(0, 0, 0, 0));
};

// 加班明细数据源
const overtimeData = ref([{
    overtimeStartTime: '',
    overtimeEndTime: '',
    week: '',
    overtimeHours: '',
    overtimeDays: '',
    attendancePeriod: ''
}])

// 加班明细表头
const overtime_columns = ref([
    { id: 'overtimeDate', label: '加班日期', width: '160' },
    { id: 'overtimeStartTime', label: '加班开始时间', width: '160' },
    { id: 'overtimeEndTime', label: '加班结束时间', width: '160' },
    { id: 'week', label: '星期', width: '160' },
    { id: 'overtimeHours', label: '加班时长（h）', width: '200' },
    { id: 'overtimeDays', label: '加班天数', width: '200' },
    { id: 'attendancePeriod', label: '归属考勤周期', width: '200' },
])

// 添加新的加班记录
const addRow = () => {
    overtimeData.value.push({
        overtimeStartTime: '',
        overtimeEndTime: '',
        week: '',
        overtimeHours: '',
        overtimeDays: '',
        attendancePeriod: ''
    })
}

// 删除指定的加班记录
const removeRow = (index) => {
    if (overtimeData.value.length <= 1) {
        ElMessage.warning('至少需要保留一条加班记录')
        return
    }
    overtimeData.value.splice(index, 1)
    calculateTotalOvertimeDays()
}

// 计算单条加班记录的信息
const calculateOvertimeInfo = (index) => {
    const row = overtimeData.value[index]

    // 验证必填项
    if (!row.overtimeStartTime || !row.overtimeEndTime) {
        row.week = ''
        row.overtimeHours = ''
        row.overtimeDays = ''
        row.attendancePeriod = ''
        return
    }

    // 获取开始时间和结束时间对象
    const startTime = new Date(row.overtimeStartTime)
    const endTime = new Date(row.overtimeEndTime)

    // 验证时间有效性
    if (isNaN(startTime.getTime()) || isNaN(endTime.getTime())) {
        row.week = ''
        row.overtimeHours = ''
        row.overtimeDays = ''
        row.attendancePeriod = ''
        return
    }

    // 计算加班时长（小时）
    const hours = (endTime - startTime) / (1000 * 60 * 60)
    row.overtimeHours = hours > 0 ? hours.toFixed(1) : '0.0'

    // 计算加班天数 - 按新规则计算
    let days = 0
    if (hours >= 8) {
        days = 1
    } else if (hours >= 4) {
        days = 0.5
    } else {
        days = 0
    }
    row.overtimeDays = days.toFixed(1)

    // 计算星期
    const dayOfWeek = startTime.getDay() // 0-6，对应周日到周六
    const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
    row.week = weekdays[dayOfWeek]

    // 计算归属考勤周期
    const year = startTime.getFullYear()
    const month = startTime.getMonth() + 1
    row.attendancePeriod = `${year}-${month.toString().padStart(2, '0')}`

    // 根据工作日历数据判断加班类型
    const dateStr = startTime.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    }).replace(/\//g, '-');

    const calendarItem = workingCalendarData.value.find(item => item.dateTime === dateStr)

    console.log(dateStr);
    console.log(calendarItem);

    if (calendarItem) {
        // 如果是法定节假日，则设置加班类型为"法定节假日"
        if (calendarItem.workingCondition === '节假日') {
            formData.value.overtimeType = '法定节假日'
        }
        // 如果是公休日，则设置加班类型为"周末"
        else if (calendarItem.workingCondition === '公休日') {
            formData.value.overtimeType = '周末'
        } else {
            // 否则，默认为工作日
            formData.value.overtimeType = '工作日'
        }
    } else {
        // 如果没有找到对应的工作日历数据，则默认为工作日
        formData.value.overtimeType = '工作日'
    }
}

// 计算总加班天数
const calculateTotalOvertimeDays = () => {
    let total = 0
    overtimeData.value.forEach(row => {
        if (row.overtimeDays && !isNaN(parseFloat(row.overtimeDays))) {
            total += parseFloat(row.overtimeDays)
        }
    })
    totalOvertimeDays.value = total.toFixed(2)
}

// 提交加班申请
const submitOvertimeApplication = () => {
    // 验证必填项
    if (!formData.value.overtimeType) {
        ElMessage.warning('请选择加班类型')
        return
    }

    if (overtimeData.value.length === 0) {
        ElMessage.warning('请至少添加一条加班记录')
        return
    }

    // 验证每条加班记录
    for (let i = 0; i < overtimeData.value.length; i++) {
        const row = overtimeData.value[i]
        if (!row.overtimeStartTime) {
            ElMessage.warning(`第${i + 1}条加班记录缺少加班开始时间`)
            return
        }
        if (!row.overtimeEndTime) {
            ElMessage.warning(`第${i + 1}条加班记录缺少加班结束时间`)
            return
        }
    }

    // 检查重复的加班时间
    const dateMap = new Map()
    for (let i = 0; i < overtimeData.value.length; i++) {
        const row = overtimeData.value[i]
        if (row.overtimeStartTime) {
            // 提取日期部分（YYYY-MM-DD）
            const dateStr = row.overtimeStartTime.split(' ')[0]
            if (dateMap.has(dateStr)) {
                ElMessage.warning(`存在重复的加班日期：${dateStr}`)
                return
            }
            dateMap.set(dateStr, true)
        }
    }

    // 提交数据
    const submitData = {
        overtimeApplications: overtimeData.value.map(row => ({
            attendanceCycle: row.attendancePeriod,
            applicationDate: formData.value.applicationDate,
            startTime: row.overtimeStartTime,
            endTime: row.overtimeEndTime,
            week: row.week,
            duration: row.overtimeHours,
            reason: textarea.value,
            overtimeType: formData.value.overtimeType,
        }))
    }

    console.log(submitData);


    // 调用API提交
    request({
        url: "/overtimeApplication/insert",
        method: "post",
        data: submitData.overtimeApplications
    }).then(resp => {
        ElMessage.success(resp.msg)
        emits('ref-table')
    }).catch(error => {
        ElMessage.error('提交失败')
    })
}

// 设置当前日期时间
const setCurrentDateTime = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    // const hours = String(now.getHours()).padStart(2, '0');
    // const minutes = String(now.getMinutes()).padStart(2, '0');
    // const seconds = String(now.getSeconds()).padStart(2, '0');
    //  ${hours}:${minutes}:${seconds}
    formData.value.applicationDate = `${year}-${month}-${day}`;
    formData.value.affiliationYear = `${year}`;
}

// 组件挂载时设置当前日期时间
onMounted(() => {
    setCurrentDateTime();
    calculateTotalOvertimeDays();
    loadAllWorkingCalendar();
})

// 保存草稿
const saveDraft = () => {
    // 实现保存草稿逻辑
    ElMessage.info('草稿已保存')
}

// 监听加班数据变化，自动计算总天数
watch(overtimeData, () => {
    calculateTotalOvertimeDays()
}, { deep: true })

// 初始化时计算总天数
calculateTotalOvertimeDays()
</script>

<style scoped>
/* 外层容器，可控制整体条的高度、圆角等 */
.progress-bar {
    height: 6px;
    background-color: #ccebf7;
    border-radius: 3px;
    display: flex;
    width: 100%;
    /* 确保进度条容器宽度占满父容器 */
    overflow: hidden;
    /* 防止子元素溢出 */
}

.progress {
    width: 8%;
    height: 10;
    background-color: #61c3ea;
    border-radius: 3px 0 0 3px;
    transition: width 0.3s ease;
    /* 添加宽度变化的过渡效果 */
}

.bottom-submit-bar {
    /* position: fixed; */
    /* 固定定位 */
    bottom: 0;
    /* 靠底部 */
    left: 0;
    width: 100%;
    background-color: #fff;
    /* 背景色，可根据需求调整 */
    border-top: 1px solid #eaeaea;
    /* 顶部边框，与页面区分 */
    padding: 12px 24px;
    /* 内边距，适配截图里的间距风格 */
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    /* 按钮靠左，可根据实际需求调整 */
    z-index: 10;
    /* 提高层级，避免被其他内容覆盖 */
}
</style>